package com.innovation.ic.im.end.base.thread.data;

import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.RedisManager;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.RabbitMqExchangeMap;
import com.innovation.ic.im.end.base.pojo.constant.RedisStorage;
import com.innovation.ic.im.end.base.service.im_erp9.UserGroupService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.thread.web.SendRabbitMqMessageThread;
import com.innovation.ic.im.end.base.value.config.RabbitMqParamConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc   将用户最近联系人的信息导入redis
 * @author linuo
 * @time   2022年10月24日13:45:48
 */
public class InsertUserCurrentDataToRedisThread extends AbstractThread implements Runnable{
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    private List<String> userNameList;
    private Boolean ifSendMqMsg = Boolean.FALSE;

    public InsertUserCurrentDataToRedisThread(List<String> userNameList, RedisManager redisManager, UserGroupService userGroupService) {
        this.userNameList = userNameList;
        this.redisManager = redisManager;
        this.userGroupService = userGroupService;
    }

    public InsertUserCurrentDataToRedisThread(List<String> userNameList, RedisManager redisManager, UserGroupService userGroupService, Boolean ifSendMqMsg, RabbitMqParamConfig rabbitMqParamConfig) {
        this.userNameList = userNameList;
        this.redisManager = redisManager;
        this.ifSendMqMsg = ifSendMqMsg;
        this.rabbitMqParamConfig = rabbitMqParamConfig;
        this.userGroupService = userGroupService;
    }

    @Override
    public void run() {
        if(userNameList != null && userNameList.size() > 0){
            for(String userName : userNameList){
                if(!Strings.isNullOrEmpty(userName)){
                    // 删除redis中的账号最近联系人数据
                    Boolean result = redisManager.delRedisDataByKeyPrefix(RedisStorage.USER_GROUP_CURRENT_PREFIX + userName);
                    if(result){
                        // 导入最新的最近联系人数据
                        ServiceResult<Boolean> serviceResult = userGroupService.insertUserCurrentDataToRedis(userName);

                        if(ifSendMqMsg && serviceResult.getResult()){
                            // 推送rabbitMq消息更新最近联系人消息
                            List<String> list = new ArrayList<>();
                            list.add(userName);
                            SendRabbitMqMessageThread sendRabbitMqMessageThread = new SendRabbitMqMessageThread(list, rabbitMqParamConfig.getExchange().get(RabbitMqExchangeMap.CURRENT_EXCHANGE), 0, userName);
                            threadPoolManager.execute(sendRabbitMqMessageThread);
                        }
                    }
                }
            }
        }
    }
}